package countdownlatch;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class CountDownLatchDemo {
	public static void main(String[] args) {
		final ExecutorService service=Executors.newCachedThreadPool();
		final CountDownLatch orderLatch=new CountDownLatch(1);
		final CountDownLatch answerLatch=new CountDownLatch(3);
		
		for(int i=0;i<3;i++){
			Runnable runnable=new Runnable() {
				
				public void run() {
					// TODO Auto-generated method stub
					System.out.println(Thread.currentThread().getName()+" 正在等待口令运行~~~");
					try {
						orderLatch.await();
						
						System.out.println(Thread.currentThread().getName()+" 收到指令，开始运行~~~");
						Thread.sleep((long) (Math.random()*5000));
						
						System.out.println(Thread.currentThread().getName()+" 运行结束~~~");
						answerLatch.countDown();
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					
				}
			};
			service.execute(runnable);
		}
		
	//控制线程	
	new Thread(new Runnable() {
		
		public void run() {
			// TODO Auto-generated method stub
			try {
				Thread.sleep((long) (Math.random()*5000));
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			System.out.println("主线程准备发布口令，通知 线程运行");
			orderLatch.countDown();
			System.out.println("主线程已经发布口令，等待其他线程运行返回～～～");
			try {
				answerLatch.await();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			System.out.println("主线程收到其他线程已经返回的信息～～～");
		}
	}).start();
	
	
	}
}
